<%@ page language="java" pageEncoding="UTF-8"%>
<%@page import="java.util.*,ll.sms.pojo.ChannelCombox,ll.sms.util.*"%>
<%@page import="ll.sms.util.AdminProperty"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>用户修改</title>
		<link rel="stylesheet" type="text/css" href="../ext/ext-all.css" />
		<link rel="stylesheet" type="text/css" href="../ext/sms.css" />
		<script type="text/javascript" src="../ext/ext-base.js"></script>
		<script type="text/javascript" src="../ext/ext-all.js"></script>
<%
String currentUserId = SmsUtil.sessionHelper(session,AdminProperty.aid);
String defaultChannelId = SmsUtil.sessionHelper(session,AdminProperty.adefaultchannel);
List<ChannelCombox> list1 = SmsUtil.getChannelList(defaultChannelId);
%>
<style type="text/css">
.settings {
	background: url(../img/delete.gif) left top no-repeat !important;
	}
.settings_c {
	background: url(../img/cancle.gif) left top no-repeat !important;
	}
</style>
<script type="text/javascript">
Ext.BLANK_IMAGE_URL = '../images/s.gif';
</script>
	<script type="text/javascript">
	window.onload=(function(){
    var simple;
    var swin;
    var store2 = new Ext.data.SimpleStore({
	fields: ['clazz', 'showname'],
	data : <%=ExtJsonBuilder.channel2ArrayStringNoAll(list1)%>
	});

	var op = new Ext.data.Store({
        proxy: new Ext.data.HttpProxy({url: '../ajaxjsp/proxycombox.jsp?adminbelong=<%=currentUserId%>'}),
        reader: new Ext.data.JsonReader({
        totalProperty: 'totalCount',
        root: 'result',
        fields :[{name:'aid'},{name:'auname'}]
        }),
        remoteSort: true
        });

function getOps(){
		   var ops = new Ext.form.ComboBox({
		   	     emptyText :'不选择或者为空将保持原值',
		         store: op,
		         width:250,
		         readOnly:true,
		         mode: 'remote',
		         triggerAction: 'all',
		         valueField: 'aid',
		         displayField: 'auname',
		         minListWidth : 80,
		         fieldLabel: '负责业务员',
                 name: 'auname_',
                 hiddenName : 'auname',
                 id:'selectoperator',
		         pageSize : 5
		     });
		     return ops;
}

function getChannelCmb(){
      var comb1 = new Ext.form.ComboBox({
          	emptyText :'不选择或者为空将保持原值',
            store: store2,
            mode:'local',
            readOnly : true,
            minListWidth : 80,
            triggerAction:'all',
            valueField: 'clazz',
            name:'uchannel_',
            id:'uchannel_',
            hiddenName : 'uchannel_1',
            displayField:'showname',
 			fieldLabel: '使用通道',
 			withd :250
            });
            return comb1;
}
	//---定义修改form
	function creatorSimpleForm(){
	 simple = new Ext.FormPanel({
	    //renderTo:'myf',
	    region: 'east',
        labelWidth: 100, // label settings here cascade unless overridden
        url:'../ajaxjsp/usereditor.jsp',
        frame:true,
        bodyStyle:'padding:5px 5px 0',
        defaultType: 'textfield',
        items: [{
                fieldLabel: '编号',
                name: 'uids',
                id:'uids',
                xtype:'hidden'
            },{
                fieldLabel: '用户名',
                name: 'uuname',
                allowBlank:false,
                blankText :'用户名必须填写'
            },{
                fieldLabel: '密码',
                name: 'upwd',
                vtype:'alphanum',
                vtypeText:'密码只能包括字母或者数字',
                xtype:'hidden',
                allowBlank:false,
                blankText :'密码必须填写'
            },{
                fieldLabel: '联系人',
                name: 'ulinkman'

            },
            {
                fieldLabel: '联系方式',
                name: 'uphone'

            },
            {
                fieldLabel: '所属代理ID',
                name: 'ucompany',
                allowBlank:false,
                blankText :'代理ID必须填写',
                xtype:'hidden'
            },
            {
                fieldLabel: '可发短信数',
                name: 'usmsnum',
                xtype:'hidden'
            },
            {
                fieldLabel: '用户等级',
                name: 'uavailable',
                xtype:'hidden'

            },{
                fieldLabel: '注册时间',
                name: 'uregisttime',
                xtype:'hidden'

            },{
            xtype: 'textarea',
            fieldLabel: '备注',
            width:'80%',
            name: 'unote'
            },
            getChannelCmb(),getOps()
        ],

        buttons: [{
            text: '修改',
            handler : function(){simple.form.submit({
					waitMsg : '正在处理......',
					success : function(form, action) {
						doReloadGrid();
						Ext.Msg.alert('成功',action.result.msg);
					},
					failure : function(form, action) {
						//form.reset();
						if (action.failureType == Ext.form.Action.SERVER_INVALID){
							Ext.MessageBox.alert('错误',action.result.errors.msg);
							}else{
							Ext.MessageBox.alert('错误','非法输入');
							}
					}
				});
            }
        }]
    });
    return simple;
	}

    //form end
 	var sm = new Ext.grid.CheckboxSelectionModel();
    sm.handleMouseDown = Ext.emptyFn;

	var AdminRecord = Ext.data.Record.create([
        {name: 'uids', type: 'string'},
        {name: 'uuname', type: 'string'},
        {name: 'upwd', type: 'string'},
        {name: 'uphone', type: 'string'},
        {name: 'ucompany', type: 'string'},
        {name: 'usmsnum', type: 'int'},
        {name: 'uavailable', type: 'int'},
        {name: 'uregisttime', type: 'string'},
        {name: 'ulinkman', type: 'string'},
        {name: 'uchannel', type: 'string'},
		{name: 'unote', type: 'string'},
		{name: 'uopname', type: 'string'}

    ]);

    var store = new Ext.data.Store({
        proxy: new Ext.data.HttpProxy({url: '../ajaxjsp/userlist.jsp'}),
        reader: new Ext.data.JsonReader({
        totalProperty: 'totalCount',
        root: 'result'
        },AdminRecord),
        remoteSort: true
    });

    var columns = new Ext.grid.ColumnModel([
        new Ext.grid.RowNumberer(),
        sm,
        {header:'充值记录',dataIndex:"chargelist",width:70,align:'center',renderer:cbutton},
        {header: '用户名', dataIndex: 'uuname',renderer:aunames},
        {header: '联系人', dataIndex: 'ulinkman'},
        {header: '联系方式', dataIndex: 'uphone'},
        {header: '可发信息数', dataIndex: 'usmsnum'},
        {header: '通道', dataIndex: 'uchannel'},
        {header: '业务员', dataIndex: 'uopname'},
        {header: '充值',dataIndex:"chargeme",width:70,align:'center',renderer:cmbutton},
        {header: '修改密码',dataIndex:"changepwd",width:70,align:'center',renderer:cpbutton}
    ]);

    columns.defaultSortable = true;

        var grid = new Ext.grid.GridPanel({
        title: '用户列表',
        region: 'center',
        loadMask: true,
        store: store,
        cm: columns,
        sm: sm,
        viewConfig: {
        columnsText:'显示的列',
        sortAscText:'升序',
        sortDescText:'降序',
        forceFit: true
        },
        bbar: new Ext.PagingToolbar({
            pageSize: 15,
            store: store,
            displayInfo: true,
            displayMsg: '显示 {0} 条到 {1} 条记录，一共 {2} 条',
            emptyMsg:'没有记录'

        }),
         tbar: new Ext.Toolbar({
        items:[
               {
                    id:'del'
                    ,text:"删除"
                    ,iconCls:'settings'
                    ,handler: function(){
                    doGrid();
                    }
                }

            ]
        })
    });

    store.load({params:{start:0,limit:15}});

    grid.on('cellclick',function (ngrid, rowIndex, columnIndex, e){
    var record = ngrid.getStore().getAt(rowIndex);   //Get the Record
    var fieldName = ngrid.getColumnModel().getDataIndex(columnIndex); //Get field name
   	if(fieldName == 'uuname'){
   	var w = showmywindow(creatorSimpleForm(),'信息修改');
   	w.show();
	simple.getForm().loadRecord(record);
   	}

   	if(fieldName == 'chargelist'){

   	var w =showmywindow(getChargeListGrid(record.get('uuname')),'充值历史');

   	w.show();
   	}

   	if(fieldName == 'chargeme'){
   	var w =showmywindow(getchargeForm(record.get('uids'),record.get('uuname')),'充值',300,150);
   	w.show();
   	}

   	if(fieldName == 'changepwd'){
   	var w =showmywindow(getchangepwdForm(record.get('uids')),'更改密码',300,200);
   	w.show();
   	}
    //var data = record.get('aid');
    //alert(data);
    //Ext.MessageBox.alert('show','当前选中的数据是'+data);
    });
	function aunames(value,c){
		return "<font style='color:red;text-decoration:underline;cursor:hand;font-color:red;'>"+value+"</font>";
	}
	function cbutton(value,c){
	  var returnStr;
      returnStr = " <button class='btn3_mouseout test' onmouseover=\"this.className='btn3_mouseover test'\" onmouseout=\"this.className='btn3_mouseout test'\" onmousedown=\"this.className='btn3_mousedown test'\" style='cursor: hand;'>充值记录</button>";
	  return returnStr;
	}

	function cmbutton(value,c){
	  var returnStr;
      returnStr = " <button class='btn3_mouseout test' onmouseover=\"this.className='btn3_mouseover test'\" onmouseout=\"this.className='btn3_mouseout test'\" onmousedown=\"this.className='btn3_mousedown test'\" style='cursor: hand;'>充值</button>";
	  return returnStr;
	}

	function cpbutton(value,c){
	  var returnStr;
      returnStr = " <button class='btn3_mouseout test' onmouseover=\"this.className='btn3_mouseover test'\" onmouseout=\"this.className='btn3_mouseout test'\" onmousedown=\"this.className='btn3_mousedown test'\" style='cursor: hand;'>修改密码</button>";
	  return returnStr;
	}

function showmywindow(obj,t,w,h){
	var tw;
	var th;

	if(w==undefined){
		tw = 500;
	}else{
		tw = w;
	}
	if(h==undefined){
		th = 300;
	}else{
		th = h;
	}

	 swin = new Ext.Window({
		title : t,
		width    : tw,
		height   : th,
		layout   : 'fit',
		//applyTo : 'panel123',
		closeAction :'close',
		items    : [obj],
		bbar    : [
			'->',
			{
			text    : '关闭',
			handler : function() {
					swin.close();
				}
			}

		]
	});
	return swin;
	}


	//##################################

	//充值
function getchargeForm(chargeedId,chargedUsername){

	var chargefield=new Ext.form.NumberField({
				fieldLabel: '充值金额',
                name: 'addcharge',
                width : '80%',
                id:'addcharge',
                xtype :'NumberField',
                allowBlank:false,
                blankText :'金额必须填写'
				});
var chargeform = new Ext.FormPanel({
        labelWidth: 80, // label settings here cascade unless overridden
        url:'../ajaxjsp/charge.jsp?opflag=u&chargeedId='+chargeedId+'&chargedUsername='+chargedUsername,
        frame:true,
        bodyStyle:'padding:5px 5px 0',
        defaultType: 'textfield',

        items: [ chargefield],
            buttons: [{
            text: '充值',
            handler : function(){chargeform.form.submit({
					waitMsg : '正在处理......',
					success : function(form, action) {
						grid.store.reload();
						Ext.Msg.alert('成功',action.result.msg);
						swin.close();
					}
					,
					failure : function(form, action) {
						if (action.failureType == Ext.form.Action.SERVER_INVALID){
							Ext.MessageBox.alert('错误',action.result.errors.msg);}else{
							Ext.MessageBox.alert('错误','---------非法输入---------');
							}
					}
				});
            }
        }]
            });
            return chargeform;
}

//*************

function getchangepwdForm(userid){
var pwdform = new Ext.FormPanel({
        labelWidth: 80, // label settings here cascade unless overridden
        url:'../ajaxjsp/usereditor.jsp?flag=changepassword&userid='+userid,
        frame:true,
        bodyStyle:'padding:5px 5px 0',
        defaultType: 'textfield',

        items: [

             {
                fieldLabel: '新密码',
                width : '80%',
                name :'pwd',
                allowBlank:false,
                blankText :'密码必须填写'
            },{
                fieldLabel: '重复新密码',
                width : '80%',
                name :'npwd',
                allowBlank:false,
                blankText :'密码必须填写'
            }

            ],
            buttons: [{
            text: '修改',
            handler : function(){pwdform.form.submit({
					waitMsg : '正在处理......',
					success : function(form, action) {
						Ext.Msg.alert('成功',action.result.msg);
					}
					,
					failure : function(form, action) {
						if (action.failureType == Ext.form.Action.SERVER_INVALID){
							Ext.MessageBox.alert('错误',action.result.errors.msg);}else{
							Ext.MessageBox.alert('错误','---------非法输入---------');
							}
					}
				});
            }
        }]
            });
       return pwdform;
}

//*************************
//获得充值列表
function getChargeListGrid(pid){

var ChargeRecord = Ext.data.Record.create([
        {name: 'cid', type: 'string'},
        {name: 'cuname', type: 'string'},
        {name: 'cprice', type: 'string'},
        {name: 'csmsnum', type: 'string'},
        {name: 'ctime', type: 'string'},
        {name: 'coperator', type: 'string'},
        {name: 'cnote', type: 'string'}


    ]);

    var store = new Ext.data.Store({
        proxy: new Ext.data.HttpProxy({url: '../ajaxjsp/chargelist.jsp?pid='+pid+'&userflag=userflag'}),
        reader: new Ext.data.JsonReader({
        totalProperty: 'totalCount',
        root: 'result'
        },ChargeRecord),
        remoteSort: true
    });

    var columns = new Ext.grid.ColumnModel([
        //{header: '编号', dataIndex: 'aid',width:1},
        new Ext.grid.RowNumberer(),
        {header: '被充值者', dataIndex: 'cuname'},
        {header: '充值', dataIndex: 'csmsnum'},
        {header: '充值时间', dataIndex: 'ctime'},
        {header: '操作员', dataIndex: 'coperator'}
        //{header: '通道密码', dataIndex: 'hpwd'}
    ]);

store.load({params:{start:0,limit:15}});
        columns.defaultSortable = true;

        var grid = new Ext.grid.GridPanel({
        loadMask: true,
        store: store,
        cm: columns,
        sm: new Ext.grid.RowSelectionModel({singleSelect:true}),
        viewConfig: {
        columnsText:'显示的列',
        sortAscText:'升序',
        sortDescText:'降序',
        forceFit: true
        },
        bbar: new Ext.PagingToolbar({
            pageSize: 15,
            store: store,
            displayInfo: true,
            displayMsg: '显示 {0} 条到 {1} 条记录，一共 {2} 条',
            emptyMsg:'没有记录'

        })
    });
return grid;
}
    //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
	var viewport = new Ext.Viewport({
	renderTo:'mt',
	layout:'border',
	items:[
	grid,
	//simple,
	{region:'south',contentEl:'inp',heigth:40}
	]
	});

	function doReloadGrid(){
	grid.store.reload();
	}

function doGrid(){
        var rows = grid.getSelectionModel().getSelections();
        if (rows.length == 0) {
            Ext.MessageBox.alert('错误', '最少选择一条信息，进行操作!');
        }
        else {
       		var names='';
                    for (var i = 0; i < rows.length; i++) {
                        names=names+rows[i].get('uuname')+',';
                    }
            Ext.MessageBox.confirm('警告', '您确定要进行用户删除操作吗？<br>即将删除的用户为【'+names+'】<br>该删除将会删除如下说明：<br><br>1、删除该用户。<br>2、删除业务员与用户的关联。<br>3、属于该代理用户的已经发送的消息以及在等待发送的消息将不会被删除。', function(btn){
                if (btn == 'yes') {
                var delid='';
                    for (var i = 0; i < rows.length; i++) {
                        delid=delid+rows[i].get('uids')+'^';
                    }
                 Ext.Ajax.request({
                  url : '../ajaxjsp/system.jsp?flag=deluser',
                  method : 'POST',
                  params : {
                      delid : delid
                  },
                  success: function(response, options) {
                        //获取响应的json字符串
                       var responseArray = Ext.util.JSON.decode(response.responseText);
                            if(responseArray.success==true){
                            	 Ext.Msg.alert('成功','操作成功');
								grid.getStore().reload();
                            }
                            else{
                                Ext.Msg.alert('失败','删除操作失败');
                            }
                         }
              });
                }
            });
        }
    }

});
	</script>
  </head>

  <body>
   <div id="mt"></div>
   <div id="north1"></div>
   <div id="south"></div>
    <div id="wait" align="center"></div>
   <input id="inp" value="刷新页面" type="button" onclick="javascript:window.location.reload();"></input>
  </body>
</html>
